package socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class Server {
    private ServerSocket serverSocket;
    private Map<String, PrintWriter> allOut = new HashMap<>();

    public Server() {
        try {
            System.out.println("正在启动服务端...");
            serverSocket = new ServerSocket(8088);
            System.out.println("服务端启动完毕...");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        try {
            while (true) {
                System.out.println("等待客户端连接...");

                Socket socket = serverSocket.accept();
                System.out.println("一个客户端连接了...");

                Runnable handler = new ClientHandler(socket);
                Thread t = new Thread(handler);
                t.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }

    private class ClientHandler implements Runnable {
        private Socket socket;
        private String host;
        private String nickname;

        public ClientHandler(Socket socket) {
            this.socket = socket;
            host = socket.getInetAddress().getHostAddress();
        }

        public void run() {
            PrintWriter pw ;
            try {
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);
                nickname = br.readLine();

                OutputStream out = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
                BufferedWriter bw = new BufferedWriter(osw);
                pw = new PrintWriter(bw, true);

                synchronized (allOut) {
                    allOut.put(nickname, pw);
                }
                broadCast(nickname + "[" + host + "]已上线,当前在线人数为:" + allOut.size());

                String message;
                while ((message = br.readLine()) != null) {
                    if (message.startsWith("@")) {
                        sendMessageToSomeone(message);
                    } else {
                        broadCast(nickname + "[" + host + "]说：" + message);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                synchronized (allOut) {
                    allOut.remove(nickname);
                }
                broadCast(nickname + "[" + host + "]已下线,当前在线人数为:" + allOut.size());

                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        private void broadCast(String massage) {
            System.out.println(massage);
            synchronized (allOut) {
                for (PrintWriter o : allOut.values()) {
                    o.println(massage);
                }
            }
        }

        public void sendMessageToSomeone(String message) {
            if (message.matches("@.+:.+")) {
                String toNickName = message.substring(1, message.indexOf(":"));

                if (allOut.containsKey(toNickName)) {
                    PrintWriter pw = allOut.get(toNickName);
                    String toMessage = message.substring(message.indexOf(":") + 1);
                    pw.println(nickname + "悄悄对你说：" + toMessage);
                } else {
                    PrintWriter pw = allOut.get(nickname);
                    pw.println("没有找到用户");
                }
            } else {
                PrintWriter pw = allOut.get(nickname);
                pw.println("格式不正确，请重新输入@对方昵称:私聊消息");
            }
        }
    }
}
